package com.greenant.store;

import java.util.HashMap;

import com.avos.avoscloud.AVUser;
import com.greenant.store.bean.EMCompany;
import com.greenant.store.bean.StoreInfo;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.utils.Const;
import com.greenant.store.utils.MyActivityLifecycleCallbacks;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

@SuppressLint("NewApi")
public class AntHomeApplication extends Application {

	/**
	 * ��װID
	 */
	public static String installationId = "";
	public static SoundPool soundPool;
	public static Context context;
	public static String newVersonName = "";
	
	public static int sCurrentGoodsCount = 0;
	
	/**
	 * 保存所有的店铺信息,每次启动的时候查询保存
	 */
	public static HashMap<String, StoreInfo> storeInfos = new HashMap<String, StoreInfo>();
	/**
	 * 保存所有快递公司信息，每次启动的时候获取
	 */
	public static HashMap<String, EMCompany> emcompanyInfos = new HashMap<String, EMCompany>();
	
	public static StoreInfo sCurrentStoreInfo;

	@Override
	public void onCreate() {

		super.onCreate();
		context = this;
		initImageLoader();
		this.registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
		// 初始化下载升级文件的路径
		Const.apkSavepath = this.getCacheDir().getAbsolutePath() + "/upgrade/";
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics metric = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(metric);
		Log.d("metric", "metric.widthPixels:" + metric.widthPixels
				+ "  metric.heightPixels:" + metric.heightPixels
				+ " metric.density:" + metric.density);

		AntHomeApplication.soundPool = new SoundPool(10,
				AudioManager.STREAM_SYSTEM, 5);

		AntHomeApplication.soundPool.load(AntHomeApplication.context,
				R.raw.facebook_ringtone_pop, 1);
		
		processInitData();

	}

	public static DisplayImageOptions imageDisplayOptions = new DisplayImageOptions.Builder()
			.resetViewBeforeLoading(false) // default
			.cacheInMemory(true) // default
			.cacheOnDisk(true) // default
			.considerExifParams(false) // default
			.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
			.bitmapConfig(Bitmap.Config.RGB_565) // default
			.displayer(new SimpleBitmapDisplayer()) // default
			.handler(new Handler(Looper.getMainLooper())) // default
			.showImageOnLoading(android.R.color.white) // resource or drawable
			.showImageForEmptyUri(android.R.color.white) // resource or drawable
			.showImageOnFail(android.R.color.white) // resource or drawable
			.build();

	private void initImageLoader() {

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).memoryCacheExtraOptions(480, 800)
				// max width, max height，即保存的每个缓存文件的最大长宽
				.threadPoolSize(10)
				// 线程池内加载的数量
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				// .diskCacheFileNameGenerator(new Md5FileNameGenerator()) //
				// 将保存的时候的URI名称用MD5 加密
				.memoryCache(new LRULimitedMemoryCache(20 * 1024 * 1024)) // You
																			// can
																			// pass
																			// your
																			// own
																			// memory
																			// cache
				// .diskCacheSize(100 * 1024 * 1024) // 100 Mb sd卡(本地)缓存的最大值
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				// 由原先的discCache -> diskCache
				.diskCache(new UnlimitedDiskCache(context.getCacheDir()))// 自定义缓存路径
				.imageDownloader(
						new BaseImageDownloader(context, 10 * 1000, 30 * 1000)) // connectTimeout
																				// (5
																				// s),
																				// readTimeout
																				// (30
																				// s)超时时间
				.defaultDisplayImageOptions(imageDisplayOptions)
				// .writeDebugLogs() // Remove for release app
				.build();
		// 全局初始化此配置

		ImageLoader.getInstance().init(config);

	}
	
	   private void processInitData()
	    {
	        RetrieveDataAsyn.getInstance().avInit(this);
	        RetrieveDataAsyn.getInstance().registerAVClass(this);

	        // 循环检测当前的登录状态，改变时发送广播
	        new Thread()
	        {
	            private boolean isLogined = false;
	            private String mUserId = "";

	            @Override
	            public void run()
	            {
	                while (true)
	                {
	                    boolean logined = isLogined;
	                    String userId = "";
	                    if (AVUser.getCurrentUser() != null)
	                    {
	                        logined = true;
	                        userId = AVUser.getCurrentUser().getObjectId();
	                    } else
	                    {
	                        logined = false;
	                        userId = "";
	                    }

	                    if (logined != isLogined)
	                    {
	                        sendBroadcast(new Intent(Const.LOGIN_STATUS_CHANGED));
	                    } else if (isLogined)
	                    {
	                        if (TextUtils.isEmpty(userId) && !userId.equals(mUserId))
	                        {
	                            sendBroadcast(new Intent(Const.LOGIN_STATUS_CHANGED));
	                        }
	                    }

	                    isLogined = logined;
	                    mUserId = userId;
	                    try
	                    {
	                        Thread.sleep(500);
	                    } catch (InterruptedException e)
	                    {
	                        e.printStackTrace();
	                    }
	                }
	            };
	        }.start();
	    }
}